package com.xnyzc.lhy.common.util;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 基本数据处理工具类
 *
 * @author liuju
 * @create 2019-07-17 13:23
 */
public class BasicDataUtil {


    private static Pattern ESCAPE_PATTERN = Pattern.compile("\\s*|\t|\r|\n");

    /**
     * List集合分页<br/>
     * 时间：2016年7月28日-下午2:58:14 <br/>
     *
     * @param <T>
     * @param pageNo
     * @param pageSize
     * @param list
     * @throws Exception List<UserOrderList> <br/>
     */
    public static <T> List<T> listPage(int pageNo, int pageSize, List<T> list) throws Exception {
        List<T> result = new ArrayList<T>();
        if (list != null && list.size() > 0) {
            int allCount = list.size();
            if (pageNo > 1 && allCount < pageSize) {
                return new ArrayList<>();
            }
            int pageCount = (allCount + pageSize - 1) / pageSize;
            if (pageNo >= pageCount) {
                pageNo = pageCount;
            }
            int start = (pageNo - 1) * pageSize;
            int end = pageNo * pageSize;
            if (end >= allCount) {
                end = allCount;
            }
            for (int i = start; i < end; i++) {
                result.add(list.get(i));
            }
        }
        return (result != null && result.size() > 0) ? result : new ArrayList<T>();
    }

    /**
     * 得到时间戳相差的年数
     *
     * @param endTime
     * @return
     * @author TaoNingBo
     */
    public static long getYearNum(Long endTime) {
        String time = DateUtil.getDateTimeYear(DateUtil.getCurMilli());
        String date = DateUtil.getDateTimeYear(endTime);
        return Long.parseLong(time) - Long.parseLong(date);
    }

    /**
     * Double类型取整
     *
     * @param num
     * @return
     */
    public static String doubleTrans(double num) {
        return String.valueOf((long) num);
    }

    /**
     * Double类型保留1位小数
     *
     * @param num
     * @return
     */
    public static String doubleRetainOne(double num) {
        DecimalFormat dfs = new DecimalFormat("0.0");
        return dfs.format(num);
    }

    /**
     * Double类型保留2位小数
     *
     * @param num
     * @return
     */
    public static String doubleRetainTwo(double num) {
        DecimalFormat dfs = new DecimalFormat("0.00");
        String.format("%.2f", num);
        return dfs.format(num);
    }

    /**
     * Double类型保留1位小数（四舍五入）
     *
     * @param num
     * @return
     */
    public static String doubleForwardOne(double num) {
        return String.format("%.1f", num);
    }

    /**
     * Double类型保留2位小数（四舍五入）
     *
     * @param num
     * @return
     */
    public static String doubleForwardTwo(double num) {
        return String.format("%.2f", num);
    }

    /**
     * 字符串转换成Ascii
     *
     * @param value
     * @return
     */
    public static String stringToAscii(String value) {
        StringBuffer sbu = new StringBuffer();
        char[] chars = value.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (i != chars.length - 1) {
                sbu.append((int) chars[i]);
            } else {
                sbu.append((int) chars[i]);
            }
        }
        return sbu.toString();
    }

    /**
     * 小数转换为百分比
     *
     * @param decimal
     * @return
     * @author TaoNingBo
     */
    public static String decTurnPercent(double decimal) {
        NumberFormat num = NumberFormat.getPercentInstance();
        num.setMaximumIntegerDigits(3);
        num.setMaximumFractionDigits(2);
        return num.format(decimal);
    }

    /**
     * Ascii转换成字符串
     *
     * @param value
     * @return
     */
    public static String asciiToString(String value) {
        String[] chars = value.split(",");
        StringBuffer sbu = new StringBuffer();
        for (int i = 0; i < chars.length; i++) {
            sbu.append((char) Integer.parseInt(chars[i]));
        }
        return sbu.toString();
    }

    /**
     * 字符串转换unicode
     *
     * @param string
     * @return
     * @author TaoNingBo
     */
    public static String string2Unicode(String string) {
        StringBuffer unicode = new StringBuffer();
        for (int i = 0; i < string.length(); i++) {
            // 取出每一个字符
            char c = string.charAt(i);
            // 转换为unicode
            unicode.append("\\u" + Integer.toHexString(c));
        }
        return unicode.toString();
    }

    /**
     * unicode 转字符串
     *
     * @param unicode
     * @return
     * @author TaoNingBo
     */
    public static String unicode2String(String unicode) {
        StringBuffer string = new StringBuffer();
        String[] hex = unicode.split("\\\\u");
        for (int i = 1; i < hex.length; i++) {
            // 转换出每一个代码点
            int data = Integer.parseInt(hex[i], 16);
            // 追加成string
            string.append((char) data);
        }
        return string.toString();
    }

    /**
     * 字符串编码转换的实现方法
     *
     * @param str        待转换编码的字符串
     * @param newCharset 目标编码
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String changeCharset(String str, String newCharset) throws UnsupportedEncodingException {
        if (str != null) {
            // 用默认字符编码解码字符串。
            byte[] bs = str.getBytes();
            // 用新的字符编码生成字符串
            return new String(bs, newCharset);
        }
        return null;
    }

    /**
     * 注： \n 回车( ) \t 水平制表符( ) \s 空格(\u0008) \r 换行( )
     *
     * @param str
     * @return
     */
    public static String replaceBlank(String str) {
        String dest = "";

        if (str != null) {
            Matcher m = ESCAPE_PATTERN.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    /**
     * 判断该字符串不能为空
     *
     * @param str
     * @return
     * @author TaoNingBo
     */
    public static boolean isNotEmpty(Object str) {
        return !isEmpty(str);
    }


    public static boolean isNotEmptyUndefined(Object str) {
        return !isEmpty(str) && !str.toString().equals("undefined");
    }

    /**
     * 字符串编码转换的实现方法
     *
     * @param str        待转换编码的字符串
     * @param oldCharset 原编码
     * @param newCharset 目标编码
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String changeCharset(String str, String oldCharset, String newCharset) throws UnsupportedEncodingException {
        if (str != null) {
            // 用旧的字符编码解码字符串。解码可能会出现异常。
            byte[] bs = str.getBytes(oldCharset);
            // 用新的字符编码生成字符串
            return new String(bs, newCharset);
        }
        return null;
    }

    /**
     * 给手机号码加分割符
     *
     * @param phone
     * @return
     * @author TaoNingBo
     */
    public static String splitPhone(String phone) {
        if (isNotEmpty(phone)) {
            String strOne = phone.substring(0, 3);
            String strTwo = phone.substring(strOne.length(), 7);
            String strThree = phone.substring(strTwo.length() + strOne.length(), phone.length());
            return strOne + "-" + strTwo + "-" + strThree;
        }
        return "";
    }

    /**
     * 非空判断
     *
     * @param str
     * @return
     * @author TaoNingBo
     */
    public static boolean isEmpty(Object str) {
        return str == null || str.toString().length() == 0 || str.equals("") || str.toString().matches("\\s*");
    }

    /**
     * 把米转换成公里
     *
     * @param m
     * @return
     * @author TaoNingBo
     */
    public static Double kmTransKilo(Integer m) {
        return Math.round(m / 100d) / 10d;
    }


    /**
     * 将List<{@link Object}>转换成List<{@link Map<String, Object>}>
     *
     * @param list
     * @return
     * @author TaoNingBo
     */
    public static List<Map<String, Object>> fromToObject_M(List<?> list) {
        List<Map<String, Object>> t = new ArrayList<Map<String, Object>>();
        for (Object object : list) {
            t.add((Map<String, Object>) object);
        }
        return t;
    }


    public static void main(String[] args) {
        // int yearNum = getYearNum(1469091228764L, 1405785600000L);
        // mData.put("json",
        // "\u0016\u0015G\u0010DC\u0016\u0015\u0012C\u0016@\u0010\u0015\u0011FLFDEEBF\u0011@MA\u0010G\u0011BC");
        // System.out.println(changeCharset("\u0016\u0015G\u0010DC\u0016\u0015\u0012C\u0016@\u0010\u0015\u0011FLFDEEBF\u0011@MA\u0010G\u0011BC",
        // "US-ASCII"));
        // System.out.println(mData.get("json"));
        // System.out.println(new Character('\\'));
        // System.err.println(decTurnPercent(0.62));
        // boolean card = checkBankCard("6222020502014733088");
        // System.err.println(card);

    }
}
